package com.vietnam.power.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.vietnam.power.dao.UserDao;
import com.vietnam.power.domain.UserPrinciple;
import com.vietnam.power.persistence.UserInfo;

@Service(value = "loginService")
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
public class LoginServiceImpl implements UserDetailsService {

	@Autowired
	private UserDao userDao;

	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		UserInfo user = userDao.getUserByUserName(username);
		List<GrantedAuthority> authorities = null;//buildUserAuthority(user.getUserRoles());

		return buildUserForAuthentication(user, authorities);
	}

	// Converts userinfo to org.springframework.security.core.userdetails.User
	private org.springframework.security.core.userdetails.User buildUserForAuthentication(UserInfo user,
			List<GrantedAuthority> authorities) {
		UserPrinciple currentUser = null;/*new UserPrinciple(user.getUserName(), user.getPassword(), user.getEnabled(),
				user.getAccountNonExpired(), user.getPasswordNonExpired(), user.getAccountNonLocked(), authorities);
		// add more info for current user
		currentUser.setId(user.getId());
		currentUser.setFirstName(user.getFirstName());
		currentUser.setLastName(user.getLastName());
		currentUser.setCountry(user.getCountry());
		currentUser.setCountryCode(user.getCountryCode());
		currentUser.setEmail(user.getEmail());
		currentUser.setGender(user.getGender());
		currentUser.setCreatedDate(user.getCreatedDate());
		currentUser.setUpdatedDate(user.getUpdatedDate());
		currentUser.setPhone(user.getPhone());
		currentUser.setTimezone(user.getTimezone());
		currentUser.setAvatarId(user.getAvatarId().getId());*/
		
		return currentUser;
	}

	// build list of roles
/*	private List<GrantedAuthority> buildUserAuthority(List<UserRole> userRoles) {
		List<GrantedAuthority> setAuths = new ArrayList<GrantedAuthority>();

		// Build user's authorities
		for (UserRole userRole : userRoles) {
			setAuths.add(new SimpleGrantedAuthority(userRole.getUserRoleInfo().getRoleName()));
		}

		return setAuths;
	}*/
}
